HOST_ARCH       ?= $(shell uname -m | sed -e s/arm.*/arm/ -e s/aarch64.*/arm64/)
ARCH            ?= $(shell uname -m | sed -e s/arm.*/arm/ -e s/aarch64.*/arm64/)
BUILD_DIR       ?= $(PWD)
_BUILD_DIR      ?= $(shell readlink -f $(BUILD_DIR))

# =========================
KERNEL_SRC        := ~/7Linux/imx6ull-kernel
ARCH              := arm
ROOT_PERMISSION   := sudo
Q                 := @
# NFS 共享目录
TFTP_SERVER       ?= ~/3tftp
NFS_SERVER        ?= ~/4nfs

TFTP_DIR          ?= $(TFTP_SERVER)
ROOTFS_ROOT_DIR   ?= $(NFS_SERVER)/imx6ull_rootfs
# ROOTFS_MODULE_DIR 可以被上层makefile中导出的同名变量覆盖
#ROOTFS_MODULE_DIR ?= $(ROOTFS_ROOT_DIR)/lib/modules/4.19.71-00007-g51f3cd8ec-dirty
ROOTFS_MODULE_DIR ?= $(ROOTFS_ROOT_DIR)/drivers_demo
# =========================
ifdef KERNEL_SRC
  KERNEL_SRC_DIR  := $(KERNEL_SRC)
else
  KERNEL_SRC_DIR  ?= /lib/modules/$(shell uname -r)/build
endif

ifeq ($(ARCH), arm)
 ifneq ($(HOST_ARCH), arm)
   CROSS_COMPILE  ?= arm-linux-gnueabihf-
 endif
endif
ifeq ($(ARCH), arm64)
 ifneq ($(HOST_ARCH), arm64)
   CROSS_COMPILE  ?= aarch64-linux-gnu-
 endif
endif

obj-m := dtbocfg.o

all:
	@# If this is an out-of-tree build, we have to create an empty makefile in the build directory
	@# (this is a hack to get around Makefile.modpost trying to include the makefile
	@#  and failing since we're doing a split build by setting src= inside the main Makefile)
	@( [ "$(BUILD_DIR)" != "$(PWD)" ] && (mkdir -p "$(BUILD_DIR)" && touch "$(BUILD_DIR)/Makefile") || true )

	$(MAKE) -C $(KERNEL_SRC_DIR) ARCH=$(ARCH) CROSS_COMPILE=$(CROSS_COMPILE) M=$(_BUILD_DIR) src=$(PWD) modules

modules_install:
	$(MAKE) -C $(KERNEL_SRC_DIR) ARCH=$(ARCH) CROSS_COMPILE=$(CROSS_COMPILE) M=$(_BUILD_DIR) src=$(PWD) modules_install

# 拷贝相关文件到nfs共享目录
install:
	$(Q)$(ROOT_PERMISSION) cp -vf *.ko $(ROOTFS_MODULE_DIR)

PHONY += clean
clean:
	$(MAKE) -C $(KERNEL_SRC_DIR) ARCH=$(ARCH) CROSS_COMPILE=$(CROSS_COMPILE) M=$(_BUILD_DIR) src=$(PWD) clean

.PHONY: $(PHONY)